<?php

namespace app\product\logic;
use app\common\library\Excel;
use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\product\model\ProductInventoryModel;
use app\common\service\CommonExportCsvTaskLogService;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;
class ProductOutLogic extends BasicLogic
{

    /**
     * @desc   获取海外仓库存列表
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function getList($params=[]){
        $limit           = getIsset($params,'limit',10);
        $spu             = getIsset($params,'spu');
        $warehouse_id    = getIsset($params,'warehouse_id');
        $where           = [];

        if($spu){
            $where[] = ['spu', '=', $spu];
        }

        if($warehouse_id){
            $where[] = ['warehouse_id', '=', $warehouse_id];
        }

        $order = ['new_quantity DESC'];
        $res   = Db::name('inventory_hwc')
            ->field('id,warehouse_id,spu,created_time')
            ->where($where)
            ->order($order)
            ->group('spu')
            ->paginate($limit);
        $list = $res->items()?:[];
        //批量获取图片地址;
        $spus = array_column($list,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');

        //获取库存总量数据;
        $info               = Db::name('inventory_hwc')->field('id,new_quantity')->where($where)->select();
        $info               = objectToArray($info);
        $total_new_quantity = array_sum(array_column($info,'new_quantity'));
        foreach($list as $k=>$v){
            //获取单个spu的库存总量数据;
            $spu_total                    = self::get_spu_info($v['spu'],$warehouse_id);
            $product_images_product       = $products_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $list[$k]['product_images'] = $display_images;
            $list[$k]['spu_quantity']   = $spu_total['total_quantity']??'0';

        }
        $data = [
            'list'                    => $list,
            'total'                   => $res->total(),
            'total_new_quantity'      => $total_new_quantity,
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);

    }


    /**
     * @desc   导出海外仓数据
     * @author luckyXiong
     * @date   2025-04-16
     */
    public function export_hwc($params=[]){
        $spu             = getIsset($params,'spu');
        $where           = [];

        if($spu){
            $where[] = ['spu', '=', $spu];
        }

        $order = ['new_quantity DESC'];
        $list  = Db::name('inventory_hwc')
            ->field('id,spu,sku,new_quantity,created_time')
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        $header[] = ['ID', 'id'];
        $header[] = ['SPU', 'spu'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['可用数量', 'new_quantity'];
        $header[] = ['创建时间', 'created_time'];
        $fileName = "export_inventory_hwc_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }











    /**
     * @desc   获取海外仓库存列表
     * @author luckyXiong
     * @date   2024-08-06
     */
    public function getSpuInfo($params=[]){
        $limit           = getIsset($params,'limit',10);
        $seller_sku      = getIsset($params,'sku');
        $spu             = getIsset($params,'spu');
        $warehouse_id    = getIsset($params,'warehouse_id');

        $where = [];

        if($seller_sku){
            $where[] = ['sku', '=', $seller_sku];
        }

        if($warehouse_id){
            $where[] = ['warehouse_id', '=', $warehouse_id];
        }

        $where[]     = ['spu', '=', $spu];

        $order = ['new_quantity DESC'];
        $res   = Db::name('inventory_hwc')
            ->field('id,warehouse_id,spu,sku,new_quantity,created_time')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];
        
        //批量获取图片地址;
        $spus = array_column($list,'spu');
        $skus_info = Db::name('product_inventory')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $skus_info_map = array_column($skus_info,null,'spu');
        foreach($list as $k=>$v){
            //获取单个spu的库存总量数据;
            $product_images = $skus_info_map[$v['spu']]??[];
            $list[$k]['product_images'] =$product_images['product_images']??'';
        }
        $data = [
            'list'                    => $list,
            'total'                   => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }



    /**
     * @desc   获取spu数据总量
     * @author luckyXiong
     * @date   2024-08-06
     */
    public function get_spu_info($spu='',$warehouse_id=''){
         $where = [];
         $where[] = ['spu','=',$spu];
         if($warehouse_id){
             $where[] = ['warehouse_id','=',$warehouse_id];
         }
         $list =  Db::name('inventory_hwc')->field('id,new_quantity')->where($where)->select();
         $list =  objectToArray($list);
         $total_quantity  = array_sum(array_column($list,'new_quantity'));
         return ['total_quantity'=>$total_quantity];
    }










    /**
     * @desc   获取海外仓库存列表
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function get_warehouse(){
        $info = Config('Logisticskey.warehouse_arr');
        $info = getLevel($info);
        $arr  = [];
        foreach($info as $v){
            $arr[] = [
                'warehouse_id'   => $v['key'],
                'warehouse_name' => $v['value'],
            ];
        }
        return json(DefaultResponse(200, true, '获取成功', $arr));
    }



    /**
     * @desc   获取海外仓库存列表
     * @author luckyXiong
     * @date   2024-08-02
     */
    public function import_jjs($url=''){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        foreach($excelData as $v){
                $exist_info = Db::name('inventory_hwc')->where(['sku'=>$v['C'],'warehouse_id'=>1])->find();
                if(!$exist_info){
                    Db::name('inventory_hwc')->insert(
                        [
                            'warehouse_id'        =>1,
                            'sku'                 =>$v['C'],
                            'inventory_quantity'  =>$v['E'],
                            'created_time'        =>date("Y-m-d H:i:s", time()),
                            'new_quantity'        =>$v['E'],
                        ]
                    );
                }else{
                    Db::name('inventory_hwc')->where('id',$exist_info['id'])->update(
                        [
                            'new_quantity'=>$v['E'],
                            'created_time'=>date("Y-m-d H:i:s", time()),
                        ]
                    );

                }
           }
    }


    /**
     * @desc   获取海外仓库存列表
     * @author luckyXiong
     * @date   2024-08-06
     */
    public function import_jinyi($url=''){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        $warehouse_arr  = [
                  '都要赢-LA'=>3,
                  '都要赢-NY'=>4,
        ];
        foreach($excelData as $v){
            $warehouse_id = $warehouse_arr[$v['E']];
            $exist_info = Db::name('inventory_hwc')->where(['sku'=>$v['C'],'warehouse_id'=>$warehouse_id])->find();
            if(!$exist_info){
                Db::name('inventory_hwc')->insert(
                    [
                        'warehouse_id'        =>$warehouse_id,
                        'sku'                 =>$v['C'],
                        'inventory_quantity'  =>$v['G'],
                        'created_time'        =>date("Y-m-d H:i:s", time()),
                        'new_quantity'        =>$v['G'],
                    ]
                );
            }else{
                Db::name('inventory_hwc')->where('id',$exist_info['id'])->update(
                    [
                        'inventory_quantity'  =>$v['G'],
                        'new_quantity'        =>$v['G'],
                        'created_time'        =>date("Y-m-d H:i:s", time()),
                    ]
                );
            }
        }
    }


    /**
     * @desc   获取海外仓库顺丰库存数据
     * @author luckyXiong
     * @date   2024-08-06
     */
    public function import_sf($url=''){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        foreach($excelData as $v){
            $exist_info = Db::name('inventory_hwc')->where(['sku'=>$v['D'],'warehouse_id'=>4])->find();
            if(!$exist_info){
                Db::name('inventory_hwc')->insert(
                    [
                        'warehouse_id'        =>4,
                        'sku'                 =>$v['D'],
                        'inventory_quantity'  =>$v['G'],
                        'created_time'        =>date("Y-m-d H:i:s", time()),
                        'new_quantity'        =>$v['G'],
                    ]
                );
            }else{
                Db::name('inventory_hwc')->where('id',$exist_info['id'])->update(
                    [
                        'new_quantity'=>$v['G'],
                        'created_time'=>date("Y-m-d H:i:s", time()),
                    ]
                );

            }
        }






    }


    /**
     * @desc   测试导出数据
     * @author luckyXiong
     * @date   2024-08-07
     */
    public function link_export($params=[]){
        try{
            $params['limit']   = 1000;
            $export_type       = $params['export_type']??'';
            $csvTaskLogService = new CommonExportCsvTaskLogService();
            $exportResult = $csvTaskLogService->operate_export_follow_data([
                new ProductInventoryModel(),
                $params,
                CommonExportCsvTaskLogService::AMAZON_EXCEPTION_LINK_EXPORT,
                $this,
                get_class($this)
            ]);
            if(empty($exportResult['status'])) {
                return $this->jsonMessage(201, false, $exportResult, null);
            }
        }catch (\Exception $e){
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }

        if($export_type=='downLoad'){
            return  $this->jsonMessage(200,true,'导出成功',$exportResult);
        }else{
            return  $this->jsonMessage(200,true,'操作成功,异步导出需要一段时间处理',null);
        }
    }



    /**
     * @desc   导出表头数据
     * @author luckyXiong
     * @date   2024-08-08
     */
    public function export_set_heading()
    {
        $values= [
            'spu'                     => 'spu',
            'seller_sku'              => 'seller_sku',
            'product_name'            => '产品名称',
            'inventory_quantity'      => '可用库存数量',
            'on_way_quantity'         => '在途数量',
            'not_send_quantity'       => '未发数量',
            'warehouse'               => '仓库',
        ];
        return $values;
    }



    /**
     * @desc   导出数据获取
     * @author luckyXiong
     * @date   2024-08-08
     */
    public function get_follow_list_export($params = [])
    {
        $params['limit']          =  1000;
        //导出三月数据处理;2022-11-03 分批次导出每次1000条
        $where =  [];
        $list  = (new ProductInventoryModel())->pageList($params);
        $export_info = $list['data'];
        //数据处理;
        $title       = self::attribute_labels_export();
        $keys        = array_keys($title);
        $values      = array_pad([], count($keys), '');
        $intersect   = array_combine($keys, $values);
        $list = [];
        foreach($export_info as $row) {
            $tmp = array_intersect_key($row, $intersect);
            $arr =arraySortByKeys($tmp, $keys);
            $list[] = $arr;
        }
        return $list;
    }



    public function attribute_labels_export(){

        return [
            'spu'                     => 'spu',
            'seller_sku'              => 'seller_sku',
            'product_name'            => '产品名称',
            'inventory_quantity'      => '可用库存数量',
            'on_way_quantity'         => '在途数量',
            'not_send_quantity'       => '未发数量',
            'warehouse'               => '仓库',
        ];
    }


}